package com.lepu.app.fun.grow;

import java.io.File;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.app.application.MyApplication;
import com.app.config.UserConfig;
import com.app.utils.Const;
import com.app.utils.SdLocal;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.utils.PopUtil;
import com.core.lib.utils.main.ImageUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.eyzhs.app.R;
import com.lepu.app.fun.grow.setting.GrowSettingAlbumImageActivity;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class GrowApplyPhotoActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, AsyncRequest,OnEditorActionListener {

	/*
	 * 网络请求，可以实现 AsyncRequest 具体例子，可以参考TestActivityMain
	 */
	private static final int MSG_APPLY_SUCCESS = 10;
	private static final int MSG_APPLY_FAIL = 11;

	private static final int MAX_LENGTH = 140;

	// 要申请相册的日期
	private String mCurrentDateString;

	private EditText mContentEditText = null;
	private TextView mCountTextView = null;
	private Button mApplyButton = null;

	private boolean mCanSend = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.grow_apply_photo_activity);

		init();
	}

	@Override
	public void onResume() {
		super.onResume();

		updateAlbumCover();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("申请热门相册");
		topbar.setonTopbarNewLeftLayoutListener(this);

		Bundle data = getIntent().getExtras();
		if (data != null && data.size() > 0) {
			mCurrentDateString = data.getString("CurrentDateString");
		}

		mApplyButton = (Button) findViewById(R.id.applyButton);
		mApplyButton.setOnClickListener(mOnClickListener);

		FrameLayout albumCoverLayout = (FrameLayout) findViewById(R.id.albumCoverLayout);
		albumCoverLayout.setOnClickListener(mOnClickListener);

		int width = UtilityBase.getWindowWidthHeight(this)[0];
		LayoutParams params = albumCoverLayout.getLayoutParams();
		params.width = width;
		params.height = width * 9 / 16;
		albumCoverLayout.setLayoutParams(params);

		mContentEditText = (EditText) findViewById(R.id.contentEditText);
		mContentEditText.setFilters(new InputFilter[] { new EmojiFilter() });
		mContentEditText.addTextChangedListener(mTextWatcher);
		mContentEditText.setOnEditorActionListener(this);

		mCountTextView = (TextView) findViewById(R.id.countTextView);
	}

	private void updateAlbumCover() {

		ImageView albumCoverImageView = (ImageView) findViewById(R.id.albumCoverImageView);
		TextView albumCoverTextView = (TextView) findViewById(R.id.albumCoverTextView);
		if (MyApplication.getInstance().checkIsLogin()) {
			LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
			String coverPath = SdLocal.getAlbumUserPath(this, loginInfo.UserID,
					"album_cover");

			if (new File(coverPath).exists()) {
				albumCoverTextView.setVisibility(View.GONE);
				UniversalImageLoadTool.disPlayNoCache("file://" + coverPath,
						albumCoverImageView, R.drawable.album_cover_default);
			} else {
				albumCoverTextView.setVisibility(View.VISIBLE);
				UniversalImageLoadTool.disPlayNoCache(ImageUtilBase
						.getDrawableImageUrl(R.drawable.album_cover_default),
						albumCoverImageView, R.drawable.album_cover_default);
			}
		} else {
			albumCoverTextView.setVisibility(View.VISIBLE);
			UniversalImageLoadTool.disPlayNoCache(ImageUtilBase
					.getDrawableImageUrl(R.drawable.album_cover_default),
					albumCoverImageView, R.drawable.album_cover_default);
		}
	}

	TextWatcher mTextWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
			int len = 0;
			int noChar = 0;

			String ss = s.toString().trim();
			for (int i = 0; i < ss.length(); i++) {
				boolean flag = UtilityBase.isChinese(ss.charAt(i));
				if (!flag)
					noChar++;
				else
					len++;
			}
			int n = noChar / 2;
			int m = noChar % 2;
			if (m == 0)
				len += n;
			else
				len += (n + 1);

			if (len <= MAX_LENGTH) {
				// len = MAX_LENGTH - len;

				// if (!mApplyButton.isEnabled())
				// mApplyButton.setEnabled(true);
				mCanSend = true;

				if (len == MAX_LENGTH) {
					// mApplyButton.setEnabled(false);
					mCanSend = false;
				}

				mCountTextView.setTextColor(getResources().getColor(
						R.color.color_text_black2));
			} else {
				// len = len - MAX_LENGTH;

				// if (mApplyButton.isEnabled())
				// mApplyButton.setEnabled(false);
				mCanSend = false;

				mCountTextView.setTextColor(getResources().getColor(
						R.color.color_text_highlight));
			}
			mCountTextView.setText(String.format("(%d/%d)", len, MAX_LENGTH));
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {

		}

		@Override
		public void afterTextChanged(Editable s) {

		}
	};

	@SuppressLint("InflateParams")
	public void showPopMoidfyAlbumCover() {
		View view = LayoutInflater.from(this).inflate(
				R.layout.grow_pop_modify_album_cover, null);
		ImageView yesImageView = (ImageView) view
				.findViewById(R.id.yesImageView);
		ImageView noImageView = (ImageView) view.findViewById(R.id.noImageView);

		yesImageView.setOnClickListener(mPopClickListener);
		noImageView.setOnClickListener(mPopClickListener);

		PopUtil.getInstance().showPopWindow(this, null, view, Gravity.BOTTOM,
				null, false);
	}

	private View.OnClickListener mPopClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			int rid = v.getId();
			switch (rid) {
			case R.id.yesImageView:
				PopUtil.getInstance().dismissPopWindow();

				Intent modifyIntent = new Intent(GrowApplyPhotoActivity.this,
						GrowSettingAlbumImageActivity.class);
				startActivity(modifyIntent, true);
				break;
			case R.id.noImageView:
				PopUtil.getInstance().dismissPopWindow();
				break;

			default:
				break;
			}
		}
	};

	View.OnClickListener mOnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			int rid = v.getId();
			switch (rid) {
			case R.id.albumCoverLayout:

				showPopMoidfyAlbumCover();
				break;
			case R.id.applyButton:

				saveContent();
				break;

			default:
				break;
			}
		}
	};

	private void saveContent() {

		boolean flag = MainTabActivity.jumpLogin(this);
		if (flag) {
			return;
		}

		String content = mContentEditText.getText().toString().trim();
		if (TextUtils.isEmpty(content)) {
			UIHelper.showToast(this, "请输入此刻的想法");
			return;
		}

		if (!mCanSend) {
			UIHelper.showToast(this, "请输入少于140个字");
			return;
		}

		if (GrowImageManager.getInstance().mIsUploading
				|| GrowApplyPhotoManager.getInstance().mIsUploading) {
			UIHelper.showToast(this, "您正在上传...");
		} else {

			UserConfig.setConfig(this, Const.CONFIG_APP_ALBUM_APPLY_DESC,
					content);

			GrowApplyPhotoManager.getInstance().init(mCurrentDateString);
			GrowApplyPhotoManager.getInstance().setIsApplyHotPhoto(true);
			GrowApplyPhotoManager.getInstance().uploadImageContent();
		}

		finish(true);
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_APPLY_SUCCESS:
				hideProgressDialog();
				finish(true);

				break;
			case MSG_APPLY_FAIL:

				hideProgressDialog();

				break;

			default:
				break;
			}
		};
	};

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		mHandler.sendEmptyMessage(MSG_APPLY_SUCCESS);
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		mHandler.sendEmptyMessage(MSG_APPLY_FAIL);
	}
	
	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		switch (actionId) {
		case EditorInfo.IME_ACTION_SEND:
			
			saveContent();
			break;
		}
		return false;
	}


}
